<template>
    <div class="spots-page">
      <!-- 1. 目的地搜索与自动补全 -->
      <div class="main-content">
        <div class="search-section">
          <input
            v-model="cityInput"
            @input="onCityInput"
            @focus="showSuggestions = true"
            @blur="hideSuggestions"
            placeholder="请输入目的地城市，如杭州"
            class="city-input"
          />
          <ul v-if="showSuggestions && filteredCities.length" class="suggestions">
            <li v-for="city in filteredCities" :key="city" @mousedown.prevent="selectCity(city)">{{ city }}</li>
          </ul>
          <button @click="searchSpots" class="search-btn">搜索</button>
        </div>
  
        <!-- 2. 景点推荐与筛选 -->
        <div v-if="selectedCity" class="filter-section">
          <span class="section-title">热门景点推荐 - {{ selectedCity }}</span>
          <div class="filters">
            <label>评分:
              <select v-model="filter.rating">
                <option value="">全部</option>
                <option value="4.5">4.5+</option>
                <option value="4.0">4.0+</option>
              </select>
            </label>
            <label>类型:
              <select v-model="filter.type">
                <option value="">全部</option>
                <option v-for="tag in allTags" :key="tag" :value="tag">{{ tag }}</option>
              </select>
            </label>
          </div>
          <div class="spot-list">
            <div v-for="spot in filteredSpots" :key="spot.id" class="spot-card">
              <img :src="spot.image" :alt="spot.name" />
              <div class="info">
                <h3>{{ spot.name }}</h3>
                <p>{{ spot.description }}</p>
                <div class="meta">
                  <span>评分: {{ spot.rating }}</span>
                  <span>类型: {{ spot.tags.join('、') }}</span>
                </div>
                <button @click="selectRouteSpot(spot)">规划路线</button>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 侧边栏 -->
      <div v-if="showSidebar" class="sidebar">
        <div class="sidebar-header">
          <h2>路线规划：{{ routeSpot.name }}</h2>
          <button class="close-btn" @click="closeSidebar">&times;</button>
        </div>
        <div class="sidebar-content">
          <!-- 选点地图容器始终存在，只用v-show控制显示 -->
          <div class="pick-map-wrap" style="position:relative;">
            <div v-show="showMapPick">
              <div class="pick-map-title">点击地图选择{{ mapPickType === 'origin' ? '起点' : '终点' }}</div>
            </div>
            <div id="pick-map" class="pick-map" v-show="showMapPick"></div>
            <div v-show="showMapPick" style="text-align:right;margin-top:8px"><button @click="closeMapPick">取消</button></div>
          </div>
          <!-- 路线表单 -->
          <div class="route-form">
            <div class="form-group">
              <label>起点：</label>
              <div class="input-group-vertical">
                <input v-model="routeStart" placeholder="如：我的位置/杭州东站" />
                <button type="button" @click="openMapPick('origin')">地图选点</button>
              </div>
            </div>
            <div class="form-group">
              <label>终点：</label>
              <div class="input-group-vertical">
                <input :value="destinationCoord ? `地图选点(${destinationCoord})` : (routeSpot ? routeSpot.name : '')" disabled />
                <button type="button" @click="openMapPick('destination')">地图选点</button>
              </div>
            </div>
            <button class="plan-btn" @click="planRoutes">生成路线</button>
          </div>
          <!-- 路线地图和详情 -->
          <div v-if="routes.length" class="route-details-wrap">
            <div id="route-map" class="route-map"></div>
            <div class="route-details">
              <div v-for="(route, idx) in routes" :key="idx" class="route-option">
                <h4>{{ route.type }}</h4>
                <p>{{ route.desc }}</p>
                <ul>
                  <li v-for="(step, i) in route.steps" :key="i">{{ step }}</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, computed, nextTick, onUnmounted } from 'vue';
  import { getSpots, getRoute } from '@/api/spot';
  
  export default {
    name: 'SpotsPage',
    setup() {
      // 城市与景点
      const cityList = ['北京', '杭州', '上海', '长沙', '广州', '深圳'];
      const cityInput = ref('');
      const showSuggestions = ref(false);
      const filteredCities = computed(() => {
        if (!cityInput.value) return [];
        return cityList.filter(city => city.includes(cityInput.value));
      });
      const selectedCity = ref('');
      function onCityInput() { showSuggestions.value = true; }
      function selectCity(city) {
        selectedCity.value = city;
        cityInput.value = city;
        showSuggestions.value = false;
        searchSpots();
      }
      function hideSuggestions() { setTimeout(() => (showSuggestions.value = false), 100); }
      const allSpots = ref([]);
      const filter = ref({ rating: '', type: '' });
      const allTags = ref([]);
      async function searchSpots() {
        if (!selectedCity.value && cityInput.value) selectedCity.value = cityInput.value;
        const res = await getSpots({ region: selectedCity.value });
        allSpots.value = res.data;
        const tags = new Set();
        res.data.forEach(s => s.tags && s.tags.forEach(t => tags.add(t)));
        allTags.value = Array.from(tags);
      }
      const filteredSpots = computed(() => {
        let spots = allSpots.value;
        if (filter.value.rating) spots = spots.filter(s => s.rating >= parseFloat(filter.value.rating));
        if (filter.value.type) spots = spots.filter(s => s.tags && s.tags.includes(filter.value.type));
        return spots;
      });
  
      // 路线规划
      const routeSpot = ref(null);
      const routeStart = ref('我的位置');
      const routes = ref([]);
      const showSidebar = ref(false);
      // 地图选点相关
      const showMapPick = ref(false);
      const mapPickType = ref('origin');
      const originCoord = ref('');
      const destinationCoord = ref('');
      let pickMap = null;
      let pickMapClickHandler = null;
      // 路线地图相关
      let routeMap = null;
      let walkingPolyline = null;
  
      function selectRouteSpot(spot) {
        routeSpot.value = spot;
        routes.value = [];
        showSidebar.value = true;
        showMapPick.value = false;
        originCoord.value = '';
        destinationCoord.value = '';
        routeStart.value = '我的位置';
        nextTick(() => {
          // 清空路线地图
          if (routeMap) {
            routeMap.destroy();
            routeMap = null;
          }
        });
      }
      function closeSidebar() {
        showSidebar.value = false;
        routeSpot.value = null;
        routes.value = [];
        showMapPick.value = false;
        if (routeMap) {
          routeMap.destroy();
          routeMap = null;
        }
        if (pickMap) {
          pickMap.destroy();
          pickMap = null;
        }
      }
      // 打开地图选点
      function openMapPick(type) {
        mapPickType.value = type;
        showMapPick.value = true;
        nextTick(() => {
          // 先销毁旧地图
          if (pickMap) {
            pickMap.destroy();
            pickMap = null;
          }
          const mapDom = document.getElementById('pick-map');
          if (!mapDom) return;
          pickMap = new window.AMap.Map('pick-map', {
            zoom: 13,
            center: [120.15507, 30.27415]
          });
          // 只绑定一次事件
          if (pickMapClickHandler) {
            pickMap.off('click', pickMapClickHandler);
          }
          pickMapClickHandler = function (e) {
            const lnglat = `${e.lnglat.getLng()},${e.lnglat.getLat()}`;
            if (mapPickType.value === 'origin') {
              originCoord.value = lnglat;
              routeStart.value = `地图选点(${lnglat})`;
            } else {
              destinationCoord.value = lnglat;
            }
            // 先移除事件监听
            pickMap.off('click', pickMapClickHandler);
            // 延迟销毁地图，确保事件处理完成
            setTimeout(() => {
              showMapPick.value = false;
              if (pickMap) {
                pickMap.destroy();
                pickMap = null;
              }
            }, 100);
          };
          pickMap.on('click', pickMapClickHandler);
        });
      }
      function closeMapPick() {
        showMapPick.value = false;
        if (pickMap) {
          pickMap.destroy();
          pickMap = null;
        }
      }
      // 路线规划
      async function planRoutes() {
        if (!originCoord.value || !destinationCoord.value) {
          routes.value = [{
            type: '路线规划失败',
            desc: '请用地图选点选择起点和终点',
            steps: []
          }];
          return;
        }
        const origin = originCoord.value;
        const destination = destinationCoord.value;
        try {
          const res = await getRoute(origin, destination);
          const data = res.data;
          if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
            const path = data.route.paths[0];
            // 渲染路线地图
            nextTick(async () => {
              if (routeMap) {
                routeMap.destroy();
                routeMap = null;
              }
              const mapDom = document.getElementById('route-map');
              if (!mapDom) return;
              // 确保地图容器可见
              mapDom.style.display = 'block';
              
              routeMap = new window.AMap.Map('route-map', {
                zoom: 14,
                center: origin.split(',').map(Number),
                viewMode: '2D'
              });
              
              // 等待地图加载完成
              await new Promise(resolve => routeMap.on('complete', resolve));
              
              if (walkingPolyline) {
                routeMap.remove(walkingPolyline);
                walkingPolyline = null;
              }
              
              const polylineArr = [];
              path.steps.forEach(step => {
                if (step.polyline) {
                  step.polyline.split(';').forEach(str => {
                    const [lng, lat] = str.split(',').map(Number);
                    polylineArr.push([lng, lat]);
                  });
                }
              });
              
              walkingPolyline = new window.AMap.Polyline({
                path: polylineArr,
                isOutline: true,
                outlineColor: '#ffeeff',
                borderWeight: 2,
                strokeColor: '#42b983',
                strokeWeight: 5,
                strokeOpacity: 0.9
              });
              
              routeMap.add(walkingPolyline);
              routeMap.setFitView([walkingPolyline]);
            });
            // 文字步骤
            const steps = path.steps.map((step, idx) => `${idx + 1}. ${step.instruction}`);
            routes.value = [{
              type: '步行推荐路线',
              desc: `全程约${path.distance}米，预计${Math.round(path.duration/60)}分钟`,
              steps
            }];
          } else {
            routes.value = [{
              type: '路线规划失败',
              desc: data.info || '未找到可用路线，建议缩短起终点距离或检查选点是否在同一城市',
              steps: []
            }];
          }
        } catch (error) {
          routes.value = [{
            type: '路线规划失败',
            desc: error.message || '获取路线数据失败',
            steps: []
          }];
        }
      }

      // 组件卸载时清理地图对象
      onUnmounted(() => {
        if (pickMap) {
          pickMap.destroy();
          pickMap = null;
        }
        if (routeMap) {
          routeMap.destroy();
          routeMap = null;
        }
      });

      return {
        cityInput, showSuggestions, filteredCities, selectedCity, onCityInput, selectCity, hideSuggestions,
        allSpots, filter, allTags, searchSpots, filteredSpots,
        routeSpot, routeStart, routes, selectRouteSpot, planRoutes,
        showSidebar, closeSidebar,
        showMapPick, openMapPick, closeMapPick, mapPickType, originCoord, destinationCoord
      };
    }
  };
  </script>
  
  <style scoped>
  .spots-page {
    max-width: 1000px;
    margin: 0 auto;
    padding: 30px 10px;
    display: flex;
  }
  .main-content {
    flex: 1;
  }
  .sidebar {
    position: fixed;
    right: 0;
    top: 0;
    width: 400px;
    height: 100vh;
    background: #f6fffa;
    border-left: 1px solid #b2e5d6;
    z-index: 1000;
    overflow-y: auto;
    box-shadow: -2px 0 8px rgba(66,185,131,0.08);
    display: flex;
    flex-direction: column;
  }
  .sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #b2e5d6;
    background: #42b983;
    color: white;
  }
  .close-btn {
    background: none;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .sidebar-content {
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .route-form {
    margin-bottom: 20px;
  }
  .form-group {
    margin-bottom: 15px;
  }
  .input-group-vertical {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .input-group-vertical input {
    padding: 8px 12px;
    border: 1px solid #b2e5d6;
    border-radius: 4px;
    background: #f6fffa;
  }
  .input-group-vertical button {
    padding: 8px 12px;
    background: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  .plan-btn {
    width: 100%;
    padding: 12px;
    background: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    margin-top: 15px;
  }
  .pick-map-wrap {
    margin-bottom: 20px;
  }
  .pick-map-title {
    font-weight: bold;
    color: #2ca06c;
    margin-bottom: 8px;
  }
  .pick-map {
    width: 100%;
    height: 220px;
    border: 1px solid #b2e5d6;
    border-radius: 4px;
    margin-bottom: 8px;
  }
  .route-details-wrap {
    margin-top: 20px;
  }
  .route-map {
    width: 100%;
    height: 200px;
    margin-bottom: 15px;
    border: 1px solid #b2e5d6;
    border-radius: 4px;
  }
  .route-details .route-option {
    margin-bottom: 15px;
  }
  .route-details h4 {
    color: #2ca06c;
    margin: 0 0 8px 0;
  }
  .route-details p {
    color: #42b983;
    margin: 0 0 10px 0;
  }
  .route-details ul {
    margin: 0;
    padding-left: 20px;
  }
  .route-details li {
    color: #666;
    margin-bottom: 5px;
  }
  /* 其余样式保持不变 */
  .search-section {
    display: flex;
    align-items: center;
    position: relative;
    margin-bottom: 20px;
  }
  .city-input {
    width: 250px;
    padding: 10px;
    border: 1px solid #b2e5d6;
    border-radius: 4px;
    font-size: 16px;
    background: #f6fffa;
  }
  .suggestions {
    position: absolute;
    top: 40px;
    left: 0;
    width: 250px;
    background: #f6fffa;
    border: 1px solid #b2e5d6;
    border-radius: 4px;
    z-index: 10;
    max-height: 180px;
    overflow-y: auto;
    box-shadow: 0 2px 8px rgba(66, 185, 131, 0.08);
  }
  .suggestions li {
    padding: 8px 12px;
    cursor: pointer;
  }
  .suggestions li:hover {
    background: #b2e5d6;
  }
  .search-btn {
    margin-left: 10px;
    padding: 10px 20px;
    background: #42b983;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  .filter-section {
    margin-bottom: 30px;
  }
  .section-title {
    font-size: 18px;
    color: #2ca06c;
    font-weight: bold;
  }
  .filters {
    margin: 10px 0 20px 0;
  }
  .filters label {
    margin-right: 20px;
    color: #42b983;
  }
  .spot-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
  }
  .spot-card {
    background: #f6fffa;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(66, 185, 131, 0.08);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    border: 1px solid #b2e5d6;
  }
  .spot-card img {
    width: 100%;
    height: 180px;
    object-fit: cover;
    border-bottom: 1px solid #b2e5d6;
  }
  .spot-card .info {
    padding: 15px;
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .spot-card h3 {
    margin: 0 0 8px 0;
    color: #2ca06c;
  }
  .spot-card .meta {
    color: #42b983;
    font-size: 13px;
    margin: 8px 0 12px 0;
  }
  .spot-card button {
    align-self: flex-end;
    padding: 6px 16px;
    background: #42b983;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  .spot-card button:hover {
    background: #2ca06c;
  }
  </style>
  